package com.chalk.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.chalk.common.util.RedisUtil;
import com.chalk.common.util.Result;
import com.chalk.config.base.BaseController;


import com.chalk.model.*;
import com.chalk.service.*;
import com.chalk.util.MapUtil;
import com.chalk.util.amap.AmapUtil;
import com.chalk.vo.TicketOrderVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Api(value = "微信小程序业务接口", tags = "微信小程序全部的业务接口")
@RestController
@RequestMapping("/v1/wxSmallRoutine")
public class WxSmallRoutineController extends BaseController {

    @Autowired
    VenueService venueService;
    @Autowired
    MemberService memberService;

    @Autowired
    SportEventService sportEventService;
    @Autowired
    VenueCommentService venueCommentService;

    @Autowired
    SignService signService;

    @Autowired
    CollectionService collectionService;

    @Autowired
    NewsTypeService newsTypeService;

    @Autowired
    NewsService newsService;

    @Autowired
    PictureService pictureService;

    @Autowired
    CoachService coachService;

    @Autowired
    TicketTypeService ticketTypeService;
    @Autowired
    TicketService ticketService;

    @Autowired
    TicketOrderService ticketOrderService;
    @Autowired
    FeedbackService feedbackService;

    @Autowired
    TicketOrderItemService ticketOrderItemService;

    /**
     * 小程序-获取推荐场馆
     *
     * @return
     */
    @GetMapping("getVenuesToList")
    public Result getVenuesToList() {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        List<Venue> venueList = venueService.getVenuesToList(1);
        //过滤场馆平均得分
        for (Venue v : venueList) {
            Double score = venueCommentService.getAvgScoreByVenueId(v.getVenueId());
            List<SportEvent> sportEvents = sportEventService.getSportEvents(v.getVenueId());
            v.setSportEvents(sportEvents);
            if (score == null) {
                v.setScoreFlag(false);
            } else {
                v.setScoreFlag(true);
                v.setScore(score);
            }
        }
        return Result.success(venueList);
    }

    /**
     * 小程序-获取运动项目
     *
     * @param map
     * @return
     */
    @GetMapping("getSportEventForPage")
    public Result getSportEventForPage(@RequestParam Map<String, Object> map) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        return Result.success(sportEventService.getSportEventForPage(MapUtil.getPage(map), MapUtil.getSize(map)));
    }

    /**
     * 小程序-通用获取场馆
     *
     * @param map
     * @return
     */
    @GetMapping("getVenuesForPage")
    public Result getVenuesForPage(@RequestParam Map<String, Object> map) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }

        Page<Venue> venuePage = venueService.getVenuesForPage(map);
        //过滤场馆平均得分
        for (Venue v : venuePage.getRecords()) {
            Double score = venueCommentService.getAvgScoreByVenueId(v.getVenueId());
            List<SportEvent> sportEvents = sportEventService.getSportEvents(v.getVenueId());
            v.setSportEvents(sportEvents);
            if (score == null) {
                v.setScoreFlag(false);
            } else {
                v.setScoreFlag(true);
                v.setScore(score);
            }
        }
        return Result.success(venuePage);
    }


    /**
     * 小程序-获取场馆的评论列表
     *
     * @param map
     * @return
     */
    @GetMapping("getVenueCommentsByVenueIdForPage")
    public Result getVenueCommentsByVenueIdForPage(@RequestParam Map<String, Object> map) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        String venueId = (String) map.get("venueId");
        if (StringUtils.isBlank(venueId)) {
            return Result.fail("venueId不能为空！");
        }

        return Result.success(venueCommentService.getVenueCommentsByVenueIdForPage(map));
    }

    /**
     * 小程序-用户签到 +10积分
     *
     * @return
     */
    @GetMapping("memberSign")
    public Result memberSign() {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        return signService.memberSign(loginMember.getMemberId());
    }

    /**
     * 小程序-用户收藏场馆
     *
     * @return
     */
    @GetMapping("collectionVenue")
    public Result collectionVenue(Integer venueId) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        if (venueId == null) {
            return Result.fail("venueId不能为空！");
        }

        return collectionService.collectionVenue(venueId, loginMember.getMemberId());
    }


    /**
     * 小程序-用户取消收藏场馆
     *
     * @param venueId
     * @return
     */
    @GetMapping("cancelCollection")
    public Result cancelCollection(Integer venueId) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        if (venueId == null) {
            return Result.fail("venueId不能为空！");
        }
        return collectionService.cancelCollection(venueId, loginMember.getMemberId());
    }

    /**
     * 小程序-获取新闻类型列表
     *
     * @return
     */
    @GetMapping("getNewsTypeToList")
    public Result getNewsTypeToList() {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        return Result.success(newsTypeService.getNewsTypeToList());
    }

    /**
     * 小程序-获取新闻分页
     *
     * @param map
     * @return
     */
    @GetMapping("getNewsForPage")
    public Result getNewsForPage(@RequestParam Map<String, Object> map) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        return Result.success(newsService.getNewsForPage(map));
    }


    /**
     * 小程序-获取轮播图
     *
     * @param map
     * @return
     */
    @GetMapping("getPicturesForPage")
    public Result getPicturesForPage(@RequestParam Map<String, Object> map) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        return Result.success(pictureService.getPicturesForPage(map));

    }

    /**
     * 小程序-获取教练分页搜索
     *
     * @param map
     * @return
     */
    @GetMapping("getCoachForPage")
    public Result getCoachForPage(@RequestParam Map<String, Object> map) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        return Result.success(coachService.getCoachForPage(map));
    }

    /**
     * 小程序-根据场馆id获取门票类型
     *
     * @param venueId
     * @return
     */
    @GetMapping("getTicketTypeToList")
    public Result getTicketTypeToList(Integer venueId) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        if (venueId == null) {
            return Result.fail("venueId不能为空！");
        }

        return Result.success(ticketTypeService.getTicketTypeToList(venueId));
    }

    /**
     * 小程序-根据票类型获取票
     *
     * @param ticketTypeId
     * @param venueId
     * @return
     */
    @GetMapping("getTicketsByTicketTypeId")
    public Result getTicketsByTicketTypeId(Integer ticketTypeId, Integer venueId) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        if (venueId == null) {
            return Result.fail("venueId不能为空！");
        }
        if (ticketTypeId == null) {
            return Result.fail("ticketTypeId不能为空！");
        }

        return Result.success(ticketService.getTicketsByTicketTypeId(ticketTypeId, venueId));
    }

    /**
     * 小程序-生成票订单
     *
     * @return
     */
    @PostMapping("generateTicketOrder")
    public Result generateTicketOrder(@RequestBody @Valid TicketOrderVo ticketOrderVo) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        if (ticketOrderVo.getTicketOrderItems().size() == 0) {
            return Result.fail("订单详情不能为空！");
        }
        if (ticketOrderService.checkTicketIsNotExist(ticketOrderVo.getTicketOrderItems())) {
            return Result.fail("有票不存在！");
        }
        if (!(ticketOrderService.checkTicketStock(ticketOrderVo.getTicketOrderItems()))) {
            return Result.fail("有票库存不足，无法提交订单！");
        }
        Boolean f = ticketOrderService.checkTicketOrderTotal(ticketOrderVo.getTicketOrderTotal(), ticketOrderVo.getTicketOrderItems());
        if (!f) {
            return Result.fail("订单金额有误，请重新提交！");
        }

        return Result.success(ticketOrderService.generateTicketOrder(ticketOrderVo, loginMember));
    }

    /**
     * 小程序-生成微信的预支付订单
     *
     * @param ticketOrderId
     * @return
     */
    @GetMapping("generateWxMiniOrder")
    public Result generateWxMiniOrder(Integer ticketOrderId) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        if (ticketOrderId == null) {
            return Result.fail("订单id不能为空！");
        }
        return Result.success(ticketOrderService.generateWxMiniOrder(ticketOrderId, loginMember));
    }

    /**
     * 小程序-支付成功回调
     *
     * @param ticketOrderId
     * @return
     */
    @GetMapping("onlinePaySuccess")
    public Result onlinePaySuccess(Integer ticketOrderId) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        if (ticketOrderId == null) {
            return Result.fail("订单id不能为空！");
        }
        return Result.success(ticketOrderService.onlinePaySuccess(ticketOrderId));
    }

    /**
     * 小程序-获取全部场馆
     *
     * @return
     */
    @GetMapping("getAllVenues")
    public Result getAllVenues(@RequestParam Map<String, Object> map) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        List<Venue> venueList = venueService.getAllVenues(map);
        //过滤场馆平均得分
        for (Venue v : venueList) {
            Double score = venueCommentService.getAvgScoreByVenueId(v.getVenueId());
            List<SportEvent> sportEvents = sportEventService.getSportEvents(v.getVenueId());
            v.setSportEvents(sportEvents);
            if (score == null) {
                v.setScoreFlag(false);
            } else {
                v.setScoreFlag(true);
                v.setScore(score);
            }
        }
        return Result.success(venueList);
    }

    /**
     * 小程序-获取我的积分
     *
     * @return
     */
    @GetMapping("getIntegral")
    public Result getIntegral() {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        return Result.success(loginMember.getIntegral());
    }

    /**
     * 小程序-签到记录分页
     *
     * @param map
     * @return
     */
    @GetMapping("memberSignPage")
    public Result memberSignPage(@RequestParam Map<String, Object> map) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        map.put("memberId", loginMember.getMemberId());
        return Result.success(signService.memberSignPage(map));

    }

    /**
     * 小程序-获取用户基本信息
     *
     * @return
     */
    @GetMapping("getMemberInfo")
    public Result getMemberInfo() {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        loginMember.setPassword("*****************************");
        return Result.success(loginMember);
    }

    /**
     * 小程序-提交反馈建议
     *
     * @param feedback
     * @return
     */
    @PostMapping("submitFeedback")
    public Result submitFeedback(@RequestBody Feedback feedback) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        if (StringUtils.isBlank(feedback.getFeedbackContent())) {
            return Result.fail("反馈内容不能为空！");
        }
        Boolean f = feedbackService.submitFeedback(feedback, loginMember);
        if (f) {
            return Result.success("提交反馈成功！");
        }
        return Result.fail("提交反馈失败！");

    }

    /**
     * 小程序-获取收藏的场馆
     *
     * @param map
     * @return
     */
    @GetMapping("getCollectionVenues")
    public Result getCollectionVenues(@RequestParam Map<String, Object> map) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        map.put("memberId", loginMember.getMemberId());

        Page<Venue> venuePage = venueService.getCollectionVenues(map);
        //过滤场馆平均得分
        for (Venue v : venuePage.getRecords()) {
            Double score = venueCommentService.getAvgScoreByVenueId(v.getVenueId());
            List<SportEvent> sportEvents = sportEventService.getSportEvents(v.getVenueId());
            v.setSportEvents(sportEvents);
            if (score == null) {
                v.setScoreFlag(false);
            } else {
                v.setScoreFlag(true);
                v.setScore(score);
            }
        }
        return Result.success(venuePage);
    }

    /**
     * 小程序-获取我的订单
     *
     * @param map
     * @return
     */
    @GetMapping("getMyTicketOrdersForPage")
    public Result getMyTicketOrdersForPage(@RequestParam Map<String, Object> map) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        Page<TicketOrder> ticketOrderPage = ticketOrderService.getMyTicketOrdersForPage(map);
        for (TicketOrder t : ticketOrderPage.getRecords()) {
            t.setTicketOrderItemList(ticketOrderItemService.getTicketOrderItems(t.getTicketOrderId()));
        }
        return Result.success(ticketOrderPage);
    }

    /**
     * 小程序-发表场馆评论
     *
     * @param comment
     * @return
     */
    @PostMapping("publishVenueComment")
    public Result publishVenueComment(@RequestBody VenueComment comment) {
        Member loginMember = memberService.selectUserDetail(getRequest());
        if (loginMember == null) {
            return Result.notLogin();
        }
        if (comment.getVenueId() == null) {
            return Result.fail("场馆id不能为空！");
        }
        comment.setMemberId(loginMember.getMemberId());
        Boolean f = venueCommentService.publishVenueComment(comment);
        return f ? Result.success("发布成功！") : Result.fail("发表失败");
    }
}
